import cache from './cache';
import { getRoleByIdAPI } from '@/services/organization';
const { role }: any = cache;

export interface RoleInfoProp {
  id: string;
  roleCode: string;
  roleName: string;
  [propsname: string]: any;
}

/**
 *  缓存角色信息
 *
 * @param {string} id 角色id
 * @param {RoleInfoProp} data 角色信息对象
 */
export const setRole = ({ id, data }: { id: string; data: RoleInfoProp }) => {
  role.set(id, data);
};

/**
 *  获取缓存的角色信息的指定字段
 *
 * @param {string} id 角色id
 * @param {string} field 指定字段名
 */
export const getRoleField = ({ id, field = 'roleName' }: { id: string; field: string }) => {
  const roleInfo = role.get(id);
  if (!roleInfo) return '';
  return roleInfo[field] || '';
};

/**
 *  获取缓存的角色信息
 *
 * @param {string} id 角色id
 */
export const getRoleInfo = (id: string) => {
  const roleInfo = role.get(id);
  if (!roleInfo) return {};
  return roleInfo;
};

/**
 *  异步获取角色信息，若缓存中存在则直接返回
 *
 * @param {string} id 角色id
 * @param {string} field 角色指定字段
 */
export const getRoleByAsync = async (id: string, field?: string) => {
  const roleInfo = role.get(id);
  if (roleInfo) return (field && roleInfo[field]) || roleInfo;
  try {
    const res = await getRoleByIdAPI({ data: { id } });
    if (!res) return;
    setRole({ id, data: res });
    return (field && res[field]) || res;
  } catch (err) {
    console.error(tr('异步获取指定角色信息失败'), err);
    return '';
  }
};
